import copy
from datetime import datetime
from flask import Blueprint, request
import requests
from utilsapp.mysql_con import db_pagelist, db_connect, db_delete, db_table_pagelist, db_update,db_insert
from utilsapp.common import assign_value, parsing_data_id
from utilsapp import utils
import json

bluePrint = Blueprint('chat', __name__)
tableName = 'chat'

def get(base,url,data,headers):
    return json.loads(requests.get(base + url, data=json.dumps(data), headers=headers).text)

def post(base,url,data,headers):
    return json.loads(requests.post(base + url, data=json.dumps(data), headers=headers).text)

@bluePrint.route('/login', methods=['GET'])
def login():
    login_data = {"username": "admin_end", "password": "78a8612541876276f1c8d5de52328f69"}
    return utils.ok(post('http://59.172.2.139:8088',"/login", login_data, {"Content-Type": "application/json"})['access_token'])

@bluePrint.route('/getlist', methods=['POST'])
def getlist():
    user_id = request.json['user_id']
    return utils.ok(db_connect(f'select * from chat where user_id = {user_id}')['data'])

@bluePrint.route('/delete', methods=['POST'])
def delete():
    id = request.json['id']
    return db_delete('chat', f'WHERE id=%s', {'id': id})

@bluePrint.route('/send', methods=['POST'])
def send():
    token = request.json['token']
    chatData = request.json['chatData']
    if chatData['id'] == 0:
        chatData['id'] = db_insert('chat',stringify(chatData))['lastrowid']
    else:
        db_update('chat',stringify(chatData),f"where id =%s", {"id_": chatData['id']})
    answer = post('http://59.172.2.139:8088',"/restful/manage/deepseek", {"question": chatData['msg'][-1]['context']}, {"Content-Type": "application/json", "Authorization": token})['answer']
    chatData['msg'].append({
        'type': 'ai',
        'time': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        'context': answer,
    })
    db_update('chat',stringify(chatData),f"where id =%s", {"id_": chatData['id']})
    return utils.ok(chatData)

def stringify(data):
    data_copy = copy.deepcopy(data)
    data_copy['msg'] = json.dumps(data_copy['msg'])
    return data_copy
    